<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="学生名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['horse:student:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['horse:student:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['horse:student:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['horse:student:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleMove"
          v-if="checkRole(['master'])"
        >迁移学生
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--      <el-table-column label="id" align="center" prop="id"/>-->
      <el-table-column label="学生名字" align="center" prop="name" />
      <el-table-column label="学生类型" align="center" prop="typeId">
        <template slot-scope="scope" >
          <el-tag v-if="scope.row.typeId==0" type="success"> 体验会员</el-tag>
          <el-tag v-if="scope.row.typeId==1" type="primary"> 正式会员</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone"/>
      <el-table-column label="身份证号码" align="center" prop="idCard"/>
      <el-table-column label="所属老师" align="center" prop="teacherName" v-if="checkRole(['common_admin','master'])"/>
      <el-table-column label="所属校长" align="center" prop="masterName" v-if="checkRole(['common_admin'])" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="checkRole(['teacher'])"  >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
             v-hasPermi="['horse:student:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['horse:student:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学生类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="选择学生类型"
            style="width: 100%"
            clearable>
            <el-option
              v-for="item in studentTypeOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入学生名字"/>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            style="width: 100%"
            placeholder="请选择出生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"/>
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCard"  >
          <el-input v-model="form.idCard" placeholder="请输入身份证号码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="迁移学生" :visible.sync="moveShow" width="700px" append-to-body>
      <el-form :model="moveForm" label-width="100px">
        <el-form-item label="老师姓名">
          <el-select
            v-model="moveForm.teacherId"
            placeholder="选择老师"
            style="width: 100%"
            filterable
            @change="teacherChange($event)">
            <el-option
              v-for="item in teacherOption"
              :label="item.nickName"
              :value="item.userId"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="this.teacherShow">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="moveForm.userName" placeholder="请输入手机号码" disabled />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMoveForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listStudent, getStudent, delStudent, addStudent, updateStudent} from "@/api/horse/student";
import {getTeacherByMasterId,moveStudent} from "@/api/horse/teacher"
// import {GetInfo} from "@/api/system/user.js"
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
//校验手机号

var  reg_tel=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
var validPhone = (rule, value, callback) => {
  if (!reg_tel.test(value)) {
    callback(new Error('手机号格式出错'));
  }else{
    callback();
  }
};

var  reg_idCard = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
var validIdCard = (rule, value, callback) => {

  if (!reg_idCard.test(value)) {
    callback(new Error('身份证格式出错'));
  }else{
    callback();
  }
};

export default {
  name: "Student",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        idCard: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [
          { validator: validPhone, trigger: 'blur' }
        ],
        idCard: [
          { validator: validIdCard, trigger: 'blur' }
        ],
      },
      studentTypeOptions:[
        {
          value:'0',
          label: '体验'
        },
        {
          value:'1',
          label: '正式'
        }
      ],
      moveShow:false,
      moveForm:{},
      teacherOption:[],
      teacherShow:false
    };
  },
  created() {
    this.getList();
    
    // this.$store.dispatch('GetInfo').then(res=>{
    //   console.log(res)
    // })
  },
  methods: {
    submitMoveForm(){
      var data={
        studentIds:this.ids,
        teacherId:this.moveForm.userId
      }
      moveStudent(data).then(res=>{
        this.$modal.msgSuccess("迁移成功");
           this.moveShow = false;
          this.getList();
      })
    },
    teacherChange(val){
        this.teacherShow=true
        var teacher=this.teacherOption.filter(teacher => teacher.userId === val)[0]
        this.moveForm = Object.assign(this.moveForm, teacher)
        console.log(this.moveForm)
    },
    getTeacherOption(){
      getTeacherByMasterId().then(res=>{
       
        this.teacherOption=res.data
      })
    },
    handleMove(){
        if(this.ids.length==0){
          this.$modal.msgWarning("请选择学生");
          return;
        }
        this.getTeacherOption()
        this.moveShow=true
        
    },

    checkPermi,
    checkRole,
    /** 查询学生列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.moveShow=false,
      this.teacherShow=false
      this.moveForm={}
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherId: null,
        typeId: null,
        name: null,
        birthday: null,
        phone: null,
        idCard: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStudent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生编号为"' + ids + '"的数据项？').then(function () {
        return delStudent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('horse/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
